import React, { Component } from 'react';
import Taro, { Config } from '@tarojs/taro';
import { View, Text, Image, Map } from '@tarojs/components'
import { AtIcon, AtActionSheet, AtActionSheetItem, AtTextarea } from 'taro-ui'
import { connect } from 'react-redux'
import map from '@/utils/map'
import alipayMap from '@/utils/alipayMap'
import { initLocation, updateStore } from '@/store/location/action'
import { createAssistance, getAssistanceOrder } from '@/api/rescue'
import { concatUrl } from '@/utils'
import { nearStore as nearStoreApi, getMapGeo } from '@/api'
const Warning = 'https://static3.jekunauto.com/img/others/warning.png'
const Car = 'https://static3.jekunauto.com/img/rescue/car.png'
const Power = 'https://static3.jekunauto.com/img/rescue/power.png'
const Charge = 'https://static3.jekunauto.com/img/rescue/charge.png'
const Change = 'https://static3.jekunauto.com/img/rescue/change.png'
const Water = 'https://static3.jekunauto.com/img/rescue/water.png'
const Trailer = 'https://static3.jekunauto.com/img/rescue/trailer.png'
const Other = 'https://static3.jekunauto.com/img/rescue/other.png'
const Select = 'https://static3.jekunauto.com/img/rescue/select.png'
const edit = require('@/static/img/edit.png')
import './index.scss'
const rescueProject = [{
  title: '紧急搭电',
  img: Power
}, {
  title: '紧急充电',
  img: Charge
}, {
  title: '换胎',
  img: Change
}, {
  title: '加水',
  img: Water
}, {
  title: '拖车',
  img: Trailer
}, {
  title: '其他',
  img: Other
}]
@connect<any>(({ location, car }) => ({ location, car }), _dispatch => ({
  // 缓存 当前区域经纬度，当前区域信息，城市名
  dispatchLocation(params) {
    return _dispatch(initLocation(params))
  },
  dispatchStore(params) {
    return _dispatch(updateStore(params))
  },
}))

export default class Index extends Component<any, any> {
  constructor () {
    super(...arguments)
    this.state = {
      location: {
        longitude: 116,
        latitude: 59
      },//当前位置
      address: null,// 调用腾讯地图api获取当前位置信息
      storeName: {},// 救援门店
      wokeTime: true,// 是否在办公时间
      wokeTimeText: '',// 营业时间范围
      selectIdx: null,// 当前选择的救援项目
      store: null,// 门店信息
      isLoading: false,//加载已完成
      editAddress: false,
    }
  }

  UNSAFE_componentWillMount() { }

  componentDidMount() {
    // 获取是否在道路救援中
    this.getAssistanceOrder()
		console.log('componentDidMount')
  }

  async UNSAFE_componentWillReceiveProps(nextProps) {
    const { address: propsAddress, storeLocation } = nextProps.location
    const { location, address, storeName } = this.state
    console.log('this------state', this)
    // 位置信息
    if (propsAddress) {
      if (propsAddress.location != location || propsAddress.address != address) {
        this.setState({
          location: {
            latitude: propsAddress.location.lat,
            longitude: propsAddress.location.lng
          },
          // address: propsAddress.address
        }
        )
      }
    }
    // 门店信息
    if (storeLocation) {
      if (storeLocation.storeCode != storeName.code || storeLocation.distance != storeName.distance) {
        this.setState({
          storeName: {
            title: storeLocation.storeName,
            code: storeLocation.storeCode,
            distance: storeLocation.distance
          }
        })
      }
    }
		console.log('storeLocation',storeLocation)
    // 营业时间范围格式化
    this.setwokeTimeText()
		console.log('UNSAFE_componentWillReceiveProps')
  }

  // 获取是否在道路救援中
  getAssistanceOrder() {
    getAssistanceOrder().then(async res => {
      const { data: { data } } = res
      if (Array.isArray(data) && data.length == 0) {
        //获取位置信息
        this.openSetting()
      } else {
        Taro.redirectTo({ url: '/pages/rescue/detail/index' })
      }
    })
  }

  // 开启定位， 需要区分微信小程序、支付宝小程序
  async openSetting(store = false) {
    const { dispatchLocation } = this.props
    let newLocation = {}
    let newStore = {}
    if (process.env.TARO_ENV === 'weapp') {
      // 获取当前位置
      const location = await map.getLocation(true)
      if (location) {
        // 调用api获取当前位置
        const result: any = await map.reverseGeocoder({
          location
        })
        newLocation = {
          city: result.ad_info.city,
          address: result.address,
          location: result.location,
          title: result.formatted_addresses.recommend
        }
        dispatchLocation(newLocation)
        const paramsData = {
          userLongitude: location.longitude,
          userLatitude: location.latitude,
          query: {
            page: 1
          }
        }
        // 获取门店信息
        await nearStoreApi(paramsData).then(res => {
          const data = res.data.data[0]
          newStore = {
            title: data.storeName,
            code: data.storeCode,
            distance: data.distance,
          }
					Taro.setStorageSync('STORE_LOCATION', data)
					this.setwokeTimeText()
        })

        this.setState({
          location,
          address: newLocation.address,
          isLoading: true,
          storeName: newStore
        }, () => {
          if (store) {
            Taro.navigateTo({ url: '/pages/store/index/index' })
          }
        })
      }
    } else { // 支付宝小程序
      // 获取当前位置
      const location = await alipayMap.getLocation(true, 3)
      console.log(location)
      if (location) {
        console.log('有没有执行到位---支付宝')
        let { city, district, streetNumber } = location
        newLocation = {
          city: city,
          address: `${city}${district}${streetNumber.street}${streetNumber.number}`,
          location: location,
          title: ''
        }
        dispatchLocation(newLocation)
        console.log('location---location', location)
        const paramsData = {
          userLongitude: location.longitude,
          userLatitude: location.latitude,
          query: {
            page: 1
          }
        }
        // 获取门店信息
        await nearStoreApi(paramsData).then(res => {
          const data = res.data.data[0]
          Taro.setStorageSync('STORE_LOCATION', data)
          newStore = {
            title: data.storeName,
            code: data.storeCode,
            distance: data.distance,
          }
        })

        this.setState({
          location,
          address: newLocation.address,
          isLoading: true,
          storeName: newStore
        }, () => {
          if (store) {
            Taro.navigateTo({ url: '/pages/store/index/index' })
          }
        })
      }
    }

  }

  // 营业时间范围格式化
  setwokeTimeText() {
    // 获取当前时，分，秒
    const date = new Date()
    const hours = date.getHours()
    const minutes = date.getMinutes()
    // 获取门店信息
    let STORE_LOCATION = Taro.getStorageSync('STORE_LOCATION')
		console.log('STORE_LOCATION',STORE_LOCATION)
    let wokeTime = false
    let wokeTimeText = "" // 营业时间范围格式化
    if (STORE_LOCATION) {
      const startTime = STORE_LOCATION.startTime.split(':')
      const endTime = STORE_LOCATION.endTime.split(':')

      // 判断当前时间是否在营业时间范围内
      if (hours >= startTime[0] && hours <= endTime[0]) {
        if (hours == startTime[0] && minutes >= startTime[1]) {
          wokeTime = true
        } else if (hours == endTime[0] && minutes <= endTime[1]) {
          wokeTime = true
        } else if (hours > startTime[0] && hours < endTime[0]) {
          wokeTime = true
        }
      }

      // 营业时间范围格式化
      wokeTimeText = STORE_LOCATION.startTime.slice(0, -3) + '~' + STORE_LOCATION.endTime.slice(0, -3)
    }
    console.log('门店时间wokeTime', wokeTime)
    console.log('门店时间wokeTimeText', wokeTimeText)
    this.setState({
      wokeTime,
      wokeTimeText
    })
  }

  // 选择服务项目
  onSelect(idx) {
    const { selectIdx } = this.state
    this.setState({
      selectIdx: selectIdx == idx ? null : idx
    })
  }

  // 确认位置
  onNext() {
    const { car: { carInfo: { currentCar } } } = this.props
    const { address, storeName: { title, code, distance }, selectIdx, location: { longitude, latitude } } = this.state
    const date = new Date()
    // 获取当前小时
    const hours = date.getHours()
    const isWokeTime = hours >= 9 && hours < 19
    if (!currentCar) {
      return Taro.navigateTo({
        url: '/pages/car/add/index'
      })
    }
    if (!isWokeTime) {
      this.setState({
        wokeTime: isWokeTime
      })
      return Taro.showToast({
        title: '非救援门店营业时间，暂不提供救援',
        icon: 'none',
        duration: 1800
      })
    }
    if (selectIdx == null) {
      return Taro.showToast({
        title: '请先选择救援项目',
        icon: 'none',
        duration: 1800
      })
    }
    if (!address || !title) {
      Taro.showToast({
        title: '请先获取位置信息',
        icon: 'none',
        duration: 1800
      })
      return this.openSetting(true)
    }
    // 距离大于10公里要提示
    if (distance > 10) {
      Taro.showModal({
        title: '温馨提示',
        content: '当前门店距离救援位置较远，建议更换附近的门店',
        success: (res) => {
          if (res.confirm) {
            // 创建救援订单
            this.createAssistance()
          }
        }
      })
    } else {
      // 创建救援订单
      this.createAssistance()
    }
  }

  // 创建救援订单
  async createAssistance() {
    const { car: { carInfo: { currentCar } } } = this.props
    let { address, storeName: { code }, selectIdx, location: { longitude, latitude } } = this.state
    const { mobile } = Taro.getStorageSync('IS_USERINFO')
    let addressLocation: any = await this.getMapGeo(longitude, latitude)
    console.log('addressLocation', addressLocation, longitude, latitude)
    longitude = addressLocation.longitude
    latitude = addressLocation.latitude
    console.log('this.props', this.props)
    if (process.env.TARO_ENV === 'weapp') { // 微信小程序
      //服务进度通知
      const WECHAT_MINI_TEMPLATE_SERVICE_PROGRESS = 'zzsYJiRq332_zi6fFyCzXCjr3qbIiR0tCNAit5fGKkE';
      //车辆完工提醒
      const WECHAT_MINI_TEMPLATE_FINISHED = 'i2byumTlAX9J6XrnfckA2LOACCjht3aUlhJdqxKYh1k';
      //订单取消通知
      const WECHAT_MINI_TEMPLATE_CANCEL_ORDER = '_1dy53eRvB7Y9FenWbhYivQDB2Rn4PHQFccpICJveSg';
      Taro.requestSubscribeMessage({
        tmplIds: [WECHAT_MINI_TEMPLATE_SERVICE_PROGRESS, WECHAT_MINI_TEMPLATE_FINISHED, WECHAT_MINI_TEMPLATE_CANCEL_ORDER],
        success: () => {
          const param = {
            type: selectIdx + 1,
            address,
            mobile,
            carLicense: currentCar.carLicense,
            storeCode: code,
            longitude: String(longitude),
            latitude: String(latitude)
          }
          // 创建救援订单
          createAssistance(param).then(() => {
            Taro.redirectTo({ url: '/pages/rescue/detail/index' })
          })
        }
      })
    } else { // 支付宝小程序
      const param = {
        type: selectIdx + 1,
        address,
        mobile,
        carLicense: currentCar.carLicense,
        storeCode: code,
        longitude: String(longitude),
        latitude: String(latitude)
      }
      // 创建救援订单
      createAssistance(param).then(() => {
        Taro.redirectTo({ url: '/pages/rescue/detail/index' })
      })
    }
  }

  // 跳转救援说明
  goMessage() {
    const obj = {
      url: '/others/roadRescue',
      path: true
    }
    Taro.navigateTo({
      url: concatUrl('/pages/webview/home/index', obj)
    })
  }

  // 拨打电话
  goDial(val) {
    if (val) {
      Taro.makePhoneCall({ phoneNumber: String(val) })
    }
  }

  inputLocation(e) {
    console.log(e)
    this.setState({
      address: e
    })
  }


  getMapGeo(longitude, latitude) {
    let storageCurrentLocation = Taro.getStorageSync('CURRENT_LOCATION_INFO')
    let { address } = this.state
    return new Promise(async (resolve, reject) => {
      if (!address) {
        console.log(11111)
        resolve({ longitude, latitude })
      } else {
        getMapGeo({
          city: storageCurrentLocation.adCode,
          address
        }).then(res => {
          let data = res.data.data
          if (!Array.isArray(data.formattedAddress)) {
            resolve({
              longitude: data.location.split(',')[0],
              latitude: data.location.split(',')[1]
            })
          } else {
            resolve({ longitude, latitude })
          }
        })
      }
    })
  }

  render() {
    const { location, address, wokeTime, wokeTimeText, selectIdx, storeName, isLoading, editAddress } = this.state
    return (
      <View className='body' style={{ paddingBottom: isLoading ? '140px' : '0px' }}>
        {
          isLoading ?
            <View>
              <View className="map">
                <Map
                  style={{ width: '100%', height: "100%" }}
                  longitude={Number(location.longitude)}
                  latitude={Number(location.latitude)}
                  showLocation
                  scale={18}
                  showCompass
                  enableTraffic
                  markers={[{
                    id: 1,
                    longitude: Number(location.longitude),
                    latitude: Number(location.latitude),
                    width: 52,
                    height: 52,
                    iconPath: Car,
                    callout: {
                      content: '救援位置',
                      color: '#FFFFFF',
                      fontSize: 14,
                      borderRadius: 60,
                      borderColor: '#FFFFFF',
                      bgColor: '#FF3B30',
                      textAlign: 'center',
                      display: 'ALWAYS',
                      padding: 8,
                      borderWidth: 0,
                    }
                  }]}
                >
                </Map>
                <View className="project">
                  <View className="project-phone">
                    <View className="phone">
                      <View className="phone-dial">客服热线：<View className="phone-dial-warning" onClick={() => this.goDial('4008-331-300')}>4008-331-300</View>,救援时间({wokeTimeText})</View>
                    </View>
                  </View>

                  <View className="project-main">
                    <View className="project-main-head">
                      <Text>请选择救援项目</Text>
                      <Text className="project-main-head-message" onClick={() => this.goMessage()}>救援说明</Text>
                    </View>
                    <View className="project-main-body">
                      {
                        rescueProject.map((item, idx) => {
                          return (
                            <View key={item.title} onClick={() => this.onSelect(idx)} className={`project-main-body-data ${selectIdx == idx ? 'select' : ''}`}>
                              <Image webp className="project-main-body-data-img" src={item.img} />
                              <View className="project-main-body-data-title" >{item.title}</View>
                              {/* 底部选中图片 */}
                              {
                                selectIdx == idx && <Image webp className="project-main-body-data-select" src={Select} />
                              }
                            </View>
                          )
                        })
                      }
                    </View>
                  </View>
                </View>
              </View>

              <View className="service">
                <View className="service-rescue" >
                  <View className="service-rescue-left">救援位置</View>
                  <View className="service-rescue-right">
                    <View className="service-rescue-right-msg ipt">
                      <View className='address'>{address ? address : '暂无定位，请授权获取位置'}</View>
                      <Image className='edit-icon' src={edit} onClick={() => { this.setState({ editAddress: true }) }}></Image>
                    </View>
                    {/* {
											address && process.env.TARO_ENV === 'weapp' && <AtIcon size="20" value='chevron-right' color='#CCCCCC'></AtIcon>
                    } */}
                  </View>
                </View>
                <View className="service-rescue" onClick={() => Taro.navigateTo({ url: '/pages/store/index/index?tabIndex=2' })}>
                  <View className="service-rescue-left">救援门店</View>
                  <View className="service-rescue-right">
                    <View className="service-rescue-right-msg">
                      {storeName && storeName.title ? `${storeName.title}(${storeName.distance}KM)` : '暂无门店'}
                    </View>
                    {
                      storeName && <AtIcon size="20" value='chevron-right' color='#CCCCCC'></AtIcon>
                    }
                  </View>
                </View>
                {
                  storeName && storeName.distance > 10 &&
                  <View className="service-warning">
                    <Image className="service-warning-icon" webp src={Warning} />
                    <Text className="service-warning-data" >当前门店距离救援位置较远，建议更换附近的门店</Text>
                  </View>
                }
              </View>
              <View className="bottom">
                {
                  wokeTime ? (address && storeName && storeName.title) ? (
                    <View className="btn" onClick={() => this.onNext()}>确认位置，下一步</View>) : (
                    <View className="btn" onClick={() => this.openSetting(true)}>授权获取位置</View>) : (
                    <View className="btn disabled" onClick={() => Taro.showToast({
                      title: '非救援门店营业时间，暂不提供救援',
                      icon: 'none',
                      duration: 1800
                    })}>非救援门店营业时间，暂不提供救援</View>
                  )
                }
              </View>
              <AtActionSheet isOpened={editAddress}>
                <AtActionSheetItem className="AtAction">
                  <View className="AtAction-title">
                    {/* <View className="AtAction-title-cancel" onClick={() => { this.setState({ editAddress: false }) }}>取消</View> */}
                    编辑地址
                  </View>
                  <View className="AtAction-message">
                    <View className='label'>救援位置</View>
                    <AtTextarea
                      value={address}
                      onChange={(val) => this.inputLocation(val)}
                      placeholderStyle="color:#999999"
                      placeholder='请输入救援位置地址'
                    />
                  </View>
                  <View className="AtAction-bottom">
                    <View className="btn" onClick={() => { this.setState({ editAddress: false }) }}>确定</View>
                  </View>
                </AtActionSheetItem>
              </AtActionSheet>
            </View> :
            // 骨架屏
            <View className="skeleton" onClick={() => this.getAssistanceOrder()}>
              <View className="skeleton-bg"></View>
              <View className="skeleton-text"></View>
              <View className="skeleton-text"></View>
              <View className="skeleton-text"></View>
              <View className="skeleton-bottom"></View>
            </View>
        }

      </View>
    )
  }
}
